﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Parser;
using Parser.StatisticsServiceClient;

namespace Statistics
{
    /// Test class to test sub routines
    /// 
    /// <author>Alexander Seeliger </author>
    public class LogProcessor
    {
        private int siteId;

        private string siteName;

        public string SiteName
        {
            get { return siteName; }
            set { siteName = value; }
        }

        private string logPath;

        public string LogPath
        {
            get { return logPath; }
            set { logPath = value; }
        }

        public int SiteId
        {
            get { return siteId; }
            set { siteId = value; }
        }

        public LogProcessor(int SiteId)
        {
            this.SiteId = SiteId;
        }

        private Parser.StatisticsServiceClient.StatisticsServiceClient client;

        public void Process()
        {
            // open web service object
            client = new Parser.StatisticsServiceClient.StatisticsServiceClient();
            client.Open();
            client.Init();

            // TODO: CHANGE THE SITE ID TO YOUR SITE ID IN THE DATABSE
            Shared.Site site = client.GetSite(1);

            // listing important informations
            logPath = site.LogPath;
            siteName = site.InternalName;

            ProcessLogFiles();

            client.Close();
        }

        /// <summary>
        /// Process all log files in the given log file directory
        /// </summary>
        private void ProcessLogFiles()
        {
            // get all log files in directory
            string[] files = System.IO.Directory.GetFiles(logPath, "*.log");

            // parse all files
            foreach (string item in files)
            {
                Shared.Logfile query = client.GetLogFile(SiteId, item);

                if (query != null)
                {
                    if (query.Processed)
                    {
                        // already completely processed, so nothing has to be done
                    }
                    else
                    {
                        // process log file
                        long finalLine =
                            ProcessLogFile(item, (long)query.CurrentLine);

                        // update files
                        query.CurrentLine = finalLine;
                        query.Processed = (DateTime.Today.Date.Subtract(GetDateFromFileName(item)).Days > 1) ? true : false;

                        client.UpdateLogFile(query);
                    }
                }
                else
                {
                    // process log file
                    long finalLine =
                        ProcessLogFile(item, 0);

                    // add files
                    Shared.Logfile newlog = new Shared.Logfile();
                    newlog.SiteId = SiteId;
                    newlog.LogFile = item;
                    newlog.CurrentLine = finalLine;
                    newlog.Processed = (DateTime.Today.Date.Subtract(GetDateFromFileName(item)).Days > 1) ? true : false;

                    client.AddLogFile(newlog);
                }
            }
        }

        /// <summary>
        /// Process a single log file
        /// </summary>
        /// <param name="LogFile">file name</param>
        private long ProcessLogFile(string LogFile, long StartLine)
        {
            // get month and year
            DateTime date = GetDateFromFileName(LogFile);

            Parser.IISHTTPParser parser = new Parser.IISHTTPParser(LogFile);
            parser.Parse(SiteName, StartLine);

            // add site reports
            foreach (KeyValuePair<string, PageProperties> item in parser.Pages)
            {
                client.AddPage(siteId, item.Key);
            }

            // add user statistics
            foreach (KeyValuePair<string, Parser.Visitor> item in parser.Visits)
            {
                client.AddVisitor(SiteId, item.Key, item.Value.VisitorFirstAction, item.Value.VisitorLastAction, 
                    item.Value.VisitorTotalAction, client.GetPage(siteId, item.Value.EntrySite), 
                    item.Value.Referer, item.Value.OS, item.Value.WebBrowser, item.Value.WebBrowserVersion, 
                    item.Value.TrafficSent, item.Value.TrafficGet, item.Value.SiteVisits, 
                    (int)item.Value.VisitorType);
            }

            return parser.CurrentLine;
        }

        private DateTime GetDateFromFileName(string LogFile)
        {
            string fileName = System.IO.Path.GetFileNameWithoutExtension(LogFile);
            fileName = fileName.Substring(2);

            return new DateTime(2000 + int.Parse(fileName.Substring(0, 2)), int.Parse(fileName.Substring(2, 2)), int.Parse(fileName.Substring(4, 2)));
        }
    }
}
